'''
Created on Jun 6, 2012

@author: thomas_dao
'''

from google.appengine.ext import ndb
from entity.entity import Ticket, UserTicket

@ndb.tasklet
def get_by_event(event_key, category=None, **q_options):
    qry = Ticket.query(Ticket.event == event_key).order(Ticket.price)
    data = yield qry.fetch_async(20, **q_options)
    raise ndb.Return(data)              


@ndb.tasklet
def get_by_user(user_key, ticket_key=None, **q_options):
    qry = UserTicket.query(UserTicket.buyer == user_key)
    if ticket_key is not None:
        qry = qry.filter(UserTicket.ticket == ticket_key)
        
    qry = qry.order(-UserTicket.created_time)
    data = yield qry.fetch_async(20, **q_options)
    raise ndb.Return(data)     


@ndb.tasklet
def count_by_event(event_key, **q_options):
    qry = Ticket.query(Ticket.event == event_key)
    count = yield qry.count_async(**q_options)
    raise ndb.Return(count)


@ndb.tasklet
def count_by_event_list(event_key_list, **q_options):
    counts = []
    for event_key in event_key_list:
        count = yield count_by_event(event_key, **q_options)
        counts.append(count)
                
    raise ndb.Return(counts)